<?php
    class papiControl{
        public function __construct() {
        }

        public function getMyWalletOp(){
           $user =  Model()->table("member")->where(["member_id" => $_SERVER['HTTP_UID']])->find();
           $setting = Model("setting")->getListSetting();
           $types = $setting["qk_type"];
           $types = mb_split("\n", $types);
           $arr = [];
           foreach ($types as $type){
               if(!empty(trim($type))){
                    $arr[] = trim($type);
               }
           }
           $ret = ["types" => $arr];
           if(is_null($user)){
               $ret["my"] = "{}";
           } else if(empty($user['qk_wallet'])){
               $ret["my"] = "{}";
           } else {
               $ret["my"] = json_decode($user["qk_wallet"], true);
           }
           echo json_encode($ret);
        }


        public function saveAddressOp(){
            $type = $_REQUEST["type"];
            $uid = $_SERVER['HTTP_UID'] ;
            $value = $_REQUEST["value"];
            $user =  Model()->table("member")->where(["member_id" => $uid])->find();
            if(empty($user["qk_wallet"])){
                $user["qk_wallet"] = "{}";
            }
            $wallet = json_decode($user["qk_wallet"], true);
            $wallet[$type] = $value;
            Model()->table("member")->where(["member_id" => $uid])->update(["qk_wallet" => json_encode($wallet)]);
            echo $uid . "ok";
        }

        public function uploadQrOp(){
//            $name = $_FILES["file"]["name"];
            $uid = $_REQUEST["uid"];
            $type = $_REQUEST["type"];
            if(strpos($_FILES['file']["type"], "image") !== false){
                $target = WEBROOT . "data/qk/personal/" . $type;
                if(!file_exists($target)){
                    @mkdir($target, 0777, true);
                }
                @copy($_FILES['file']["tmp_name"], $target . '/' . $uid . '.jpg');
            }
            echo "ok";
        }

        public function qrcodeOp(){
            $t0 = $_REQUEST["t0"];
            $t1 = $_REQUEST["t1"];
            $t2 = $_REQUEST["t2"];
            $target = WEBROOT . "data/qk/" . $t0 . "/" . $t1 . "/" . $t2 . ".jpg";
            if(file_exists($target)){
                $img = $target;
                $info = getimagesize($img);
                $imgExt = image_type_to_extension($info[2], false); //获取文件后缀
                $fun = "imagecreatefrom{$imgExt}";
                $imgInfo = $fun($img);         //1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename )
                $mime = $info['mime'];
//                $mime = image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型
                header('Content-Type:'.$mime);
                $quality = 100;
                if($imgExt == 'png') $quality = 9;   //输出质量,JPEG格式(0-100),PNG格式(0-9)
                $getImgInfo = "image{$imgExt}";
                $getImgInfo($imgInfo, null, $quality); //2.将图像输出到浏览器或文件。如: imagepng ( resource $image )
                imagedestroy($imgInfo);
            } else {
                echo "no";
            }
        }

        /**
         * 重新计算某个用户的订单
         */
        public function fixOrderOp(){
            $orders = Model()->query("select * from ra_order where buyer_id = $_REQUEST[uid] and qk_fixed_order = 0 order by order_id desc limit 5");
            foreach($orders as $order){
                //调取该订单下所有商品
                $goods = Model()->query("select g.*, og.goods_pay_price as price, og.goods_num as num from ra_goods g inner join ra_order_goods og on og.goods_id = g.goods_id where og.order_id = " . $order["order_id"]);
                $total = $order["order_amount"];
                $qktotal = 0;
                $qk_reward_total = 0;
                $qk_total_unit = "";
                foreach($goods as $g){
                    //计算商品总金额
                    if($g["qk_pay_full"] == 1){
                        $total -= $g["price"] * $g["num"];
                    }
                    $qktotal += $g['qk_pay_money'] * $g['num'] ;
                    $qk_reward_total += $g["qk_reward_money"] * $g["num"];
                    if(!empty($g["qk_pay_unit"]) && empty($qk_total_unit)){
                        $qk_total_unit = $g["qk_pay_unit"];
                    }
                }
                if($total <= 0){
                    $this->payOrder($order);
                } else {

                }
                Model()
                    ->table("order")
                    ->where(["order_id" => $order["order_id"]])
                    ->update([
                        "qk_order" => $qktotal > 0 ? 1 : 0, "qk_total" => $qktotal, "qk_reward_total" => $qk_reward_total,
                        "order_amount" => $total,
                        "qk_fixed_order" => 1,
                        "qk_total_unit" => $qk_total_unit
                    ]);
            }
        }

        /**
         * 将一个订单标为支付状态
         * @param $oinfo
         */
        private function payOrder($oinfo){
            require_once __DIR__ . "/payment.php";
            $_GET["noreturn"] = 1;
            $_GET["payment_code"] = "manual";
            $_POST['extra_common_param'] = "real_order";
            $_POST['out_trade_no'] = $oinfo["pay_sn"];
            $paymentControl = new paymentControl();
            $paymentControl->notifyOp();
            Model()->table("order")->where([
                "order_id" => $oinfo["order_id"],
            ])->update([
                "payment_code" => "manual"
            ]);
        }


        public function getOrderQkOp(){
            //订单详情
            $oinfo = Model()
                ->table("order")
                ->field("store_id,qk_order,qk_total,qk_reward_total,qk_total_unit,qk_buyer_confirm,qk_seller_confirm,qk_buyer_message")
                ->where([
                "order_id" => $_GET["id"],
            ])->find();
            //商家收款信息
            $sinfo = Model()
                ->table("store")
                ->where([
                    "store_id" => $oinfo["store_id"]
                ])
                ->field("qk_wallet_config")
                ->find();
            if(empty($sinfo["qk_wallet_config"])){
                $sinfo["qk_wallet_config"] = '{}';
            }
            $qk_wallet_config = json_decode($sinfo["qk_wallet_config"], true);
            echo json_encode([
                "orderInfo" => $oinfo,
                "qk_wallet_config" => $qk_wallet_config
            ]);
        }


        public function buyerConfirmOp(){
            $order = Model()
                ->table("order")
                ->where([
                    "order_id" => $_GET["id"],
                    "qk_buyer_confirm" => 0
                ])->find();
            if(empty($order)){
                echo "failed";
                return;
            }
            Model()
                ->table("order")
                ->where([
                    "order_id" => $_GET["id"],
                ])
                ->update([
                    "qk_buyer_confirm" => 1,
                    "qk_buyer_message" => $_GET["message"]
                ]);
            echo "ok";
        }


        public function getGoodsQkOp(){
            $json = (file_get_contents('php://input'));
            $buyInfo = json_decode($json, true)["buyInfo"];
            $ids = join(",", array_keys($buyInfo));
            $gs = Model()
                ->table("goods")
                ->where([
                    "goods_id" => ["in", $ids]
                ])
                ->select();
            $ret = [];
            foreach($gs as $g){
                if(($g["qk_pay_money"] <= 0)){
                    continue;
                }
                $ret[$g["goods_id"]] = [
                    "qk_pay_money" => $g["qk_pay_money"] * $buyInfo[$g["goods_id"]],
                    "qk_pay_unit" => $g["qk_pay_unit"],
                    "qk_pay_full" => $g["qk_pay_full"]
                ] ;
            }
            echo json_encode($ret);
        }

        public function getGoodsQkInfoOp(){
            $json = (file_get_contents('php://input'));
            $gids = json_decode($json, true);
            $ginfos = Model()
                ->table("goods")
                ->field("qk_pay_money,qk_pay_full,qk_pay_unit,goods_id")
                ->where([
                    "goods_id" => ["in", $gids]
                ])
                ->select();
//            $ret = [];
//            foreach ($ginfos as $g){
//                $ret[$g["goods_id"]] = $g;
//            }
            echo json_encode($ginfos);
        }


        public function getUserPointLogOp(){
//            if(empty($_GET["start"])){
//                $_GET["start"] = 0;
//            }
//            $where = [
//                "pl_memberid" => $_GET["uid"]
//            ];
            $where = "";
            if(!empty($_GET["key"])){
//                $where["pl_state"] = $_GET["key"];
                $where = " and pl_stage = '$_GET[key]'";
            }
            $size = 20;
            $offset = ($_GET["page"] - 1) * $size;
            $sql = "select pl_addtime,pl_desc,pl_points from ra_points_log where pl_memberid=$_GET[uid] $where order by pl_addtime limit $offset, $size";
            $res = Model()->query($sql);
            if(!$res){
                $res = [];
            }
            foreach ($res as &$val){
                $val['pl_addtime'] = date("Y-m-d H:i:s", $val["pl_addtime"]);
            }
//                ->table("points_log")
//                ->field("pl_addtime,pl_desc,pl_points")
//                ->where($where)
//                ->order("pl_addtime desc")
//                ->page(1)
//                ->limit(20)//$_GET["page"])
//                ->select();
            echo json_encode($res);
        }
    }
?>